package com.example.weiwing.Loginmain;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.translation.TranslationResponseValue;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONPathTypedMultiNamesPrefixIndex1;
import com.example.weiwing.R;
import com.example.weiwing.config.WeiWingConfig;
import com.kongzue.baseokhttp.HttpRequest;
import com.kongzue.baseokhttp.listener.ResponseListener;
import com.kongzue.baseokhttp.util.JsonMap;

import java.util.regex.Pattern;

public class LoginEdit extends AppCompatActivity {

    private EditText et_username;
    private EditText et_nickname;
    private EditText et_email;
    private EditText et_telephone;
    private RadioGroup rg_gender;
    private EditText et_password;
    private EditText et_password_confirm;

    private Handler mHandler;
    private Button btn_register;
    private CheckBox cb_agree;
    private RadioButton rd_male;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_edit);

        et_username = findViewById(R.id.et_username);
        et_nickname = findViewById(R.id.et_nickname);
        et_email = findViewById(R.id.et_email);
        et_telephone = findViewById(R.id.et_telephone);
        rg_gender = findViewById(R.id.rg_gender);
        rd_male = findViewById(R.id.rb_male);
        et_password = findViewById(R.id.et_password);
        et_password_confirm = findViewById(R.id.et_password_confirm);
        btn_register = findViewById(R.id.btn_register);
        cb_agree = findViewById(R.id.cb_agree);

        mHandler = new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                if (msg.what == 1) {

                } else if (msg.what == 2) {
                    Intent it = new Intent(LoginEdit.this, Login.class);
                    it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(it);
                }
            }
        };

        et_username.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String username = charSequence.toString();
                checkUsernameValid(username);
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });


        et_nickname.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String nickname = charSequence.toString();
                checkNicknameValid(nickname);
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        et_email.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String email = charSequence.toString();
                checkEmailValid(email);
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        et_telephone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String telephone = charSequence.toString();
                checkTelephoneValid(telephone);
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        et_password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String password = charSequence.toString();
                checkPasswordValid(password);
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        et_password_confirm.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String password = et_password.getText().toString();
                String passwordRepeat = charSequence.toString();
                checkPasswordRepeatValid(password, passwordRepeat);
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        btn_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkUsernameValid(et_username.getText().toString());
                if (et_username.getError() != null) {
                    et_username.requestFocus();
                    et_username.setSelection(et_username.getText().toString().length());
                    return;
                }
                checkNicknameValid(et_nickname.getText().toString());
                if (et_nickname.getError() != null) {
                    et_nickname.requestFocus();
                    et_nickname.setSelection(et_nickname.getText().toString().length());
                    return;
                }
                checkEmailValid(et_email.getText().toString());
                if (et_email.getError() != null) {
                    et_email.requestFocus();
                    et_email.setSelection(et_email.getText().toString().length());
                    return;
                }
                checkTelephoneValid(et_telephone.getText().toString());
                if (et_telephone.getError() != null) {
                    et_telephone.requestFocus();
                    et_telephone.setSelection(et_telephone.getText().toString().length());
                    return;
                }
                checkPasswordValid(et_password.getText().toString());
                if (et_password.getError() != null) {
                    et_password.requestFocus();
                    et_password.setSelection(et_password.getText().toString().length());
                    return;
                }
                checkPasswordRepeatValid(et_password.getText().toString(), et_password_confirm.getText().toString());
                if (et_password_confirm.getError() != null) {
                    et_password_confirm.requestFocus();
                    et_password_confirm.setSelection(et_password_confirm.getText().toString().length());
                    return;
                }

                if (!cb_agree.isChecked()) {
                    Toast.makeText(LoginEdit.this,"请勾选用户协议", Toast.LENGTH_SHORT).show();
                    return;
                }

                String username = et_username.getText().toString();
                String nickname = et_nickname.getText().toString();
                String email = et_email.getText().toString();
                String phone = et_telephone.getText().toString();
                int gender = rd_male.isChecked() ? 0 : 1;
                String password = et_password.getText().toString();
                new RegistThread(username, nickname, email, phone, gender, password).start();
            }
        });
    }

    private void checkPasswordRepeatValid(String password, String passwordRepeat) {
        if (!passwordRepeat.equals(password)) {
            et_password_confirm.setError("两次输入密码不一致");
        }
    }


    private void checkPasswordValid(String password) {
        if (isvalid(password, "^[\\w!@#$%^&*-]{6,18}$")) {
        } else {
            et_password.setError("密码为字母、数字、@#$%^&*-_组合，长度为6-18位");
        }
        String passwordRepeat = et_password_confirm.getText().toString();
        if (!passwordRepeat.isEmpty()) {
            checkPasswordRepeatValid(passwordRepeat, password);
        }
    }

    private void checkTelephoneValid(String telephone) {
        if (isvalid(telephone, "^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\\d{8}$")) {
        } else {
            et_telephone.setError("电话格式错误");
        }
    }

    private void checkEmailValid(String email) {
        if (isvalid(email, "^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$")) {
        } else {
            et_email.setError("邮箱格式错误");
        }
    }

    private void checkNicknameValid(String nickname) {
        if (isvalid(nickname, "^[\\u4E00-\\u9FA5\\uF900-\\uFA2D\\w-]{1,18}$")) {
        } else {
            et_nickname.setError("昵称为中文、字母、数字、_、-组合，长度为1-18位");
        }
    }

    private void checkUsernameValid(String username) {
        if (isvalid(username, "^[A-Za-z0-9]{5,18}$")) {
            new CheckUsernameUniqueThread(username).start();
        } else {
            et_username.setError("用户名为字母或数字，长度为5-18位");
        }
    }


    private boolean isvalid(String str, String reg) {
        if (str != null && !str.isEmpty()) {
            return Pattern.matches(reg, str);
        }
        return false;
    }

    public class CheckUsernameUniqueThread extends Thread {

        private String username;

        public CheckUsernameUniqueThread(String username) {
            this.username = username;
        }

        @Override
        public void run() {
            super.run();
            HttpRequest.build(LoginEdit.this, WeiWingConfig.getUrl() + "/user/checkUserName")
                    .addParameter("username", username)
                    .setResponseListener(new ResponseListener() {
                        @Override
                        public void onResponse(String response, Exception error) {
                            if (error == null) {
                                JSONObject jsonObject = JSONObject.parseObject(response);
                                Integer code = jsonObject.getInteger("code");
                                if (code == 200) {
                                } else {
                                    et_username.setError("用户名已存在");
                                }
                            } else {

                            }
                        }
                    }).doPost();
        }
    }

    public class RegistThread extends Thread {

        private String username;

        private String nickname;
        private String email;
        private String phone;
        private int gender;
        private String password;

        public RegistThread(String username, String nickname, String email, String phone, int gender, String password) {
            this.username = username;
            this.nickname = nickname;
            this.email = email;
            this.phone = phone;
            this.gender = gender;
            this.password = password;
        }

        @Override
        public void run() {
            super.run();
            JsonMap jsonMap = new JsonMap();
            jsonMap.set("userName", username);
            jsonMap.set("nickName", nickname);
            jsonMap.set("email",email);
            jsonMap.set("phone",phone);
            jsonMap.set("gender", gender);
            jsonMap.set("password", password);
            HttpRequest.build(LoginEdit.this, WeiWingConfig.getUrl() + "/user/regist")
                    .setJsonParameter(jsonMap)
                    .setResponseListener(new ResponseListener() {
                        @Override
                        public void onResponse(String response, Exception error) {
                            if (error == null) {
                                JSONObject jsonObject = JSONObject.parseObject(response);
                                Integer code = jsonObject.getInteger("code");
                                if (code == 200) {
                                    Toast.makeText(LoginEdit.this,"注册成功", Toast.LENGTH_SHORT).show();
                                    mHandler.obtainMessage(2).sendToTarget();
                                } else {
                                    String msg =jsonObject.getString("msg");
                                    Toast.makeText(LoginEdit.this,msg, Toast.LENGTH_SHORT).show();
                                }
                            } else {

                            }
                        }
                    }).doPost();
        }
    }

}